package com.equdao.car_violation_inquiry.controller;

import com.equdao.car_violation_inquiry.pojo.*;
import com.equdao.car_violation_inquiry.service.BasicCarService;
import com.equdao.car_violation_inquiry.service.LocalService;
import com.equdao.car_violation_inquiry.service.WebPageService;
import com.equdao.car_violation_inquiry.service.impl.WebPageViolationHistoryServiceImpl;
import com.equdao.car_violation_inquiry.utils.CookieUtil;
import com.equdao.car_violation_inquiry.utils.CsvUtils;
import com.equdao.car_violation_inquiry.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: 杨忠强
 * @Date: 2018/6/19 9:48
 * @Description:
 */
@Controller
public class WebPageController {

    //1.上传csv(判断格式)
//    3.返回唯一标识
//    2.读取csv到数据库(并存入唯一标识)
//    4根据唯一标识导出异常活成功数据
    //引入service
    @Autowired
    private BasicCarService basicCarService;

    @Autowired
    private WebPageService webPageService;

    @Autowired
    private WebPageViolationHistoryServiceImpl webPageViolationHistoryService;





    @PostMapping("/uploadBaseViolationCar")
    public String smartQueryViolationRecord(@RequestParam MultipartFile pictureFile, HttpServletResponse response) throws Exception {
        Result result;

        //获取上传csv的名称
        String oldFileName = pictureFile.getOriginalFilename();
        //组装新图片名称
        String newFileName = "";
        //获取当前时间
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
        String date = df.format(new Date());

        //判断是否为.csv文件
        if (".csv".equals(oldFileName.substring(oldFileName.lastIndexOf(".")))) {
            newFileName = date + "_" + oldFileName;
            //图片保存到一个路径
            pictureFile.transferTo(new File("C:\\Users\\Administrator\\Desktop\\" + newFileName));
            System.out.println("新文件名称:" + newFileName);
            //读取本地的csv文件
            ArrayList<BasicCarDO> basicCarDOList = CsvUtils.getCsvInfo("C:\\Users\\Administrator\\Desktop\\" + newFileName, oldFileName, newFileName);
            //TODO 判断切割完的格式是否为三个字符串


            System.out.println("csv表格中所有行数：" + basicCarDOList.size());
            //将数据批量写入数据库中
            int average = basicCarDOList.size() / 1000;
            System.out.println("总数" + basicCarDOList.size());

            System.out.println("总共" + average +"批数据");
            int remainder = basicCarDOList.size() % 1000;
            System.out.println("余数" + remainder);

            for (int j = 0; j < average +1  ; j++) {
                if (j < average){
                    List<BasicCarDO> basicCarDOS =  basicCarDOList.subList(1000 * j, 1000 * (j + 1));
                    Integer integer = basicCarService.saveBasicCar(basicCarDOS);
                }else {
                    List<BasicCarDO> basicCarDOS =  basicCarDOList.subList(1000 * j, basicCarDOList.size());
                    Integer integer = basicCarService.saveBasicCar(basicCarDOS);
                }
                System.out.println("写入了" + (j+1) + "次");
            }

            // TODO  上传基本信息表后  添加一张记录表


            WebPageViolationHistoryDO webPageViolationHistoryDO = new WebPageViolationHistoryDO();
            webPageViolationHistoryDO.setFileName(oldFileName);
            webPageViolationHistoryDO.setFlag(newFileName);
            webPageViolationHistoryService.saveWebPageViolationHistory(webPageViolationHistoryDO);




        } else {
            result = ResultUtil.error(1, "上传文件格式错误,请返回重新操作");
        }
        Cookie fileCookie = new Cookie("flag",newFileName);
        fileCookie.setMaxAge(900);
        response.addCookie(fileCookie);
        return "common/flag.html";
    }


    @ResponseBody
    @GetMapping("/runViolation")
    public Result uploadBaseCarData(String flag, Integer threadNumber) {
        Result result;
        //前端传来批次号 以及线程数
        System.out.println(flag);
        String origin = "恒达";
        System.out.println(threadNumber);

        // 1.读取将要接口查询的数据
        List<BasicCarDO> list = basicCarService.findBasicCarListByFlag(flag,"0");
        int average = list.size() / threadNumber;
        System.out.println("总数" + list.size());

        System.out.println("平均值" + average);
        int remainder = list.size() % threadNumber;
        System.out.println("余数" + remainder);

        for (int i = 0; i < threadNumber; i++) {
            if (i != threadNumber - 1) {
                List<BasicCarDO> basicCarDOList = list.subList(average * i, average * (i + 1));
                startRequest(origin, i, basicCarDOList);
            } else {
                List<BasicCarDO> basicCarDOList = list.subList(average * i, average * (i + 1) + remainder);
                startRequest(origin, i, basicCarDOList);
            }
        }

        result = ResultUtil.success(null);
        return result;
    }



/**
 * 查询历史批次号
 * */
    @ResponseBody
    @GetMapping("/findHistoryFlag")
    public Result findHistoryFlag(HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        Result result;
        List<WebPageViolationHistoryDO> webPageViolationHistory = webPageViolationHistoryService.findWebPageViolationHistory();
        result = ResultUtil.success(webPageViolationHistory);
        return result;
    }


    /**
     * 根据批次号查询历史违章进度
     * */
    @ResponseBody
    @PostMapping("/findProgressRate")
    public Result findProgressRate(String flag,HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        //flag  输出
        System.out.println(flag);

        Result result;

        Integer total = basicCarService.findBasicCarTotal(flag);

        Integer completed = basicCarService.findBasicCarCompleted(flag,"1");

        ProgressDTO progressDTO = new ProgressDTO();
        progressDTO.setTotal(total);
        progressDTO.setCompleted(completed);

        result = ResultUtil.success(progressDTO);
        return result;
    }



    private void startRequest(String origin, int i, List<BasicCarDO> basicCarDOList) {
        if ("恒达".equals(origin)) {
            System.out.println("第" + (i + 1) + "部分:" + basicCarDOList.size() + "条");
            Integer issusses = webPageService.findHDViolationInfo(basicCarDOList);
        }
//        else if ("万物".equals(origin)) {
//            System.out.println("第" + (i + 1) + "部分:" + basicCarDOList.size() + "条");
//            Integer issusses = webPageService.findWWViolationInfo(basicCarDOList);
//
//        }
    }


}
